package com.nidu.demo.mail.executor.command;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.mail.ability.MailTemplateDomainService;
import com.nidu.demo.mail.convertor.MailTemplateConvertor;
import com.nidu.demo.mail.dto.MailTemplateAddCmd;
import com.nidu.demo.mail.dto.MailTemplateCO;
import com.nidu.demo.mail.dto.MailTemplateUpdateCmd;
import com.nidu.demo.mail.gateway.MailTemplateGateway;
import com.nidu.demo.mail.model.MailTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 邮件模板添加命令执行器
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class MailTemplateUpdateCmdExe {

    private final MailTemplateConvertor convertor;
    private final MailTemplateGateway gateway;
    private final MailTemplateDomainService domainService;

    @Transactional
    public SingleResponse<MailTemplateCO> execute(MailTemplateUpdateCmd cmd) {
        // 1. 校验模板编码是否重复
        domainService.validateDuplicate(cmd.getTemplateCode(), cmd.getId());

        // 2. 转换为领域对象
        MailTemplate mailTemplate = MailTemplate.update(cmd.getId(), cmd.getTemplateName(), cmd.getTemplateCode(), cmd.getAccountId(),
                cmd.getTemplateNickname(), cmd.getTemplateTitle(), cmd.getTemplateContent(), cmd.getRemark());

        // 3. 保存邮件模板
        MailTemplate saved = gateway.create(mailTemplate);

        // 4. 转换为DTO返回
        MailTemplateCO mailTemplateCO = convertor.toClientObject(saved);
        return SingleResponse.of(mailTemplateCO);
    }

}
